import {
  exportCheckData,
  mGetDevCheckHistoryData,
  mSelectDevIsFixedParam,
} from '@/api/device'
import useGlobalAPI from '@/hooks/useGlobalAPI'
import {FormInstance} from 'ant-design-vue'
import dayjs, {Dayjs} from 'dayjs'
import {PropType} from 'vue'
import {downFile} from '@/libs/toolkit'
import CoustomForm from '@/components/form'
import {debounce} from '@/libs/debounce'
import {CoustomTableFn} from '@/components/table'

//? 状态管理区 -----------------------------------
/**字典类型 状态数据 */
interface Device_xxx_List {
  /**所有检测参数 */
  device_param_list: SysDict.Item[]
}
interface Device_checkHistory_state extends Device_xxx_List {
  table: {
    dataSource: Device.HistoryCheckData[]
    pagination: Paging
    total: number
    loading: boolean
    pagination_handle: Function
  }
  /**弹窗 */
  modal: {
    /**弹窗 关闭*/
    visible: boolean
    /**弹窗 类型*/
    type: 'exportCheckData' | null
    /**弹窗 标题*/
    title: string
    /**导出历史记录日期范围选择 数据源 */
    exportCheckData_source: {
      startTime: Dayjs | null
      endTime: Dayjs | null
    }
  }
  search: {
    devId: number | null
    startDate: Dayjs
    endDate: Dayjs
  }
  checkDevInfo: {devId: number; devName: string} | null
  /**true:固定参数 false:非固定参数 */
  isFixedParam: boolean
}
export let device_checkHistory_state = reactive<Device_checkHistory_state>({
  device_param_list: [],
  table: {
    dataSource: [],
    pagination: {
      page: 1,
      size: 20,
    },

    total: 0,
    loading: false,
    pagination_handle: (page: number, size: number) => {
      let {pagination} = toRefs(device_checkHistory_state.table)
      pagination.value.page = page
      pagination.value.size = size
      getTableDatas()
    },
  },
  search: {
    devId: null,
    startDate: dayjs(),
    endDate: dayjs(),
  },
  checkDevInfo: null,
  isFixedParam: false,
  modal: {
    visible: false,
    type: null,
    title: '',
    exportCheckData_source: {
      startTime: null,
      endTime: null,
    },
  },
})

//? 接口调用区 -----------------------------------
/**获取表格数据 */
export const getTableDatas = debounce(async () => {
  let {search} = toRefs(device_checkHistory_state)
  if (!search.value.devId) return
  let {
    dataSource,
    pagination,
    total: tableTotal,
    loading,
  } = toRefs(device_checkHistory_state.table)
  loading.value = true
  let defaultData = {
    page: 1,
    size: 20,
    start: 0,
    devId: search.value.devId,
    startDate: search.value.startDate?.format('YYYY-MM-DD 00:00:00') as string,
    endDate: search.value.endDate?.format('YYYY-MM-DD 23:59:59') as string,
  }

  Object.assign(defaultData, pagination.value)
  let res = await mGetDevCheckHistoryData(defaultData).catch(err => {})
  loading.value = false
  if (!res) return
  let {list, total} = res.data
  dataSource.value = list
  tableTotal.value = total
}, 300)

/**检验当前设备id是否是固定数据 */
export const checkIsFixedParamByDevId = async () => {
  let {checkDevInfo, isFixedParam} = toRefs(device_checkHistory_state)
  if (!checkDevInfo.value?.devId) return
  let res = await mSelectDevIsFixedParam({
    devId: checkDevInfo.value?.devId,
  }).catch(err => {})
  if (res) {
    switch (res.data) {
      case '1':
        console.log('固定参数历史记录')
        isFixedParam.value = true
        break
      case '2':
        console.log('非固定参数历史记录')
        isFixedParam.value = false
        break
    }
    getTableDatas()
  }
}

//? 组件事件区 -----------------------------------
/**获取路由传参传递过来的currentDevInfo */
export const handle_currentDevInfo_by_route_params_currentDevInfo =
  (currentDevInfo?: {devId: number; devName: string}) => {
    if (currentDevInfo) {
      let {checkDevInfo, search, isFixedParam} = toRefs(
        device_checkHistory_state
      )
      let {page} = toRefs(device_checkHistory_state.table.pagination)
      checkDevInfo.value = currentDevInfo
      search.value.devId = checkDevInfo.value.devId
      isFixedParam.value = false
      page.value = 1
      checkIsFixedParamByDevId()
    } else {
      getTableDatas()
    }
  }

//? 复用组件区 -----------------------------------

//? 页面组件区 -----------------------------------

/**检测数据 非固定参数 左侧搜索 头部 */
export const CheckHistoryViewLeftNav = defineComponent({
  name: 'CheckHistoryViewLeftNav',
  setup() {
    let {router} = useGlobalAPI()

    return () => (
      <div class="w-full h-full">
        <a-button
          class="w-full h-full"
          onClick={() => {
            router.push({name: 'device-list'})
          }}
        >
          前往设备列表
        </a-button>
      </div>
    )
  },
})

/**检测数据 非固定参数 左侧搜索 主体视窗 */
export const CheckHistoryViewLeft = defineComponent({
  name: 'CheckHistoryViewLeft',
  setup() {
    let {checkDevInfo} = toRefs(device_checkHistory_state)
    let {page} = toRefs(device_checkHistory_state.table.pagination)
    let {startDate, endDate} = toRefs(device_checkHistory_state.search)

    let formRef = ref<FormInstance>()
    let state_form = reactive<{
      dateRange: [Dayjs, Dayjs]
    }>({
      dateRange: [dayjs(), dayjs()],
    })
    watch(
      () => [startDate.value, endDate.value],
      n => {
        page.value = 1
      }
    )

    watch(
      () => state_form.dateRange,
      n => {
        console.log(n)
        startDate.value = n[0]
        endDate.value = n[1]
      }
    )

    /**提交表单且数据验证成功后回调事件 */
    const handle_viewLeftFilter_form_finish = async () => {
      getTableDatas()
    }

    /** 提交表单且数据验证失败后回调事件 */
    const handle_viewLeftFilter_form_finish_failed = () => {
      viewLeftFilter_returnEmit()
    }

    /**表单 重置按钮 点击 */
    const handle_viewLeftFilter_form_reset = debounce(() => {
      viewLeftFilter_returnEmit()
      setTimeout(() => {
        getTableDatas()
      })
    }, 200)

    // 清空表单 关闭外层弹框
    const viewLeftFilter_returnEmit = () => {
      formRef.value?.resetFields()
      page.value = 1
    }

    return () => (
      <a-form
        class="h-full viewLeftFilter overflow-auto relative"
        v-model={[formRef, 'ref']}
        name="addSysdictType"
        model={state_form}
        label-col={{span: 8}}
        wrapper-col={{span: 16}}
        onFinish={handle_viewLeftFilter_form_finish}
        onFinishFailed={handle_viewLeftFilter_form_finish_failed}
      >
        <a-form-item label="设备名称" class="mx-2 my-4">
          <div class="truncate">
            {checkDevInfo.value?.devName ? (
              <a-tooltip title={checkDevInfo.value?.devName}>
                {checkDevInfo.value?.devName}
              </a-tooltip>
            ) : (
              '请选择设备'
            )}
          </div>
        </a-form-item>
        <a-form-item
          name="dateRange"
          class="mx-2 my-4"
          label-col={{span: 0}}
          wrapper-col={{span: 24}}
        >
          <a-range-picker
            v-model={[state_form.dateRange, 'value']}
            format="YYYY/MM/DD"
          />
        </a-form-item>
        <div class="w-full h-mainViewfooter absolute left-0 bottom-0 m-0 px-4 border-t border-default flex justify-end items-center">
          <a-button type="primary" onClick={handle_viewLeftFilter_form_reset}>
            重置
          </a-button>
          <a-button class="ml-4 " type="primary" html-type="submit">
            查询
          </a-button>
        </div>
      </a-form>
    )
  },
})

/**检测数据 非固定参数 表格 上方操作栏 */
export const CheckHistoryMainViewNav = defineComponent({
  setup() {
    let {router} = useGlobalAPI()
    let {checkDevInfo, isFixedParam} = toRefs(device_checkHistory_state)

    const handle_export_btn_click = () => {
      let {visible, type, title, exportCheckData_source} = toRefs(
        device_checkHistory_state.modal
      )
      type.value = 'exportCheckData'
      title.value = '导出历史记录(不选择日期默认导出全部)'
      visible.value = true
    }

    /**前往固定参数分析页 */
    const handle_router_to_checkHistory_isFixedParam = () => {
      router.push({
        path: '/device/list/checkHistory/fixedParam',
        query: {
          devId: checkDevInfo.value?.devId,
          devName: checkDevInfo.value?.devName,
        },
      })
    }

    return () => (
      <div class="w-full h-full flex justify-end items-center">
        <a-button
          class={[
            checkDevInfo.value?.devId
              ? 'block transition mx-2'
              : 'w-0 overflow-hidden p-0 m-0 border-0',
          ]}
          type="primary"
          onClick={handle_export_btn_click}
        >
          历史记录导出
        </a-button>
        <a-button
          type="primary"
          class={[
            isFixedParam.value
              ? 'mr-4 float-right mx-2'
              : 'w-0 overflow-hidden m-0 p-0 border-0',
          ]}
          onClick={handle_router_to_checkHistory_isFixedParam}
        >
          查看具体参数分析
        </a-button>
      </div>
    )
  },
})

/**检测数据 非固定参数 表格 */
const CoustomTable = CoustomTableFn<Device.HistoryCheckData>()
export const CheckHistoryTable = defineComponent({
  setup(props) {
    let {dataSource, loading, total, pagination_handle} = toRefs(
      device_checkHistory_state.table
    )
    let {page, size} = toRefs(device_checkHistory_state.table.pagination)
    type Key = string | number
    /**表格头 */
    let columns: CColumn<Device.HistoryCheckData>[] = [
      {
        title: '序号',
        dataIndex: 'index',
        isIndex: true,
        ellipsis: true,
        width: 100,
      },
      {
        title: '检测时间',
        dataIndex: 'devCheckTime',
        width: 200,
      },
      {
        title: '检测信息',
        dataIndex: 'checkdataList',
      },
    ]

    return () => (
      <CoustomTable
        dataSource={dataSource.value}
        loading={loading.value}
        columns={columns}
        pagination={{
          page: page.value,
          size: size.value,
          total: total.value,
        }}
        rowKey="devCheckId"
        onPaginationChange={({page, size}) => {
          pagination_handle.value(page, size)
        }}
      >
        {{
          bodyCell: (
            text: string,
            record: Device.HistoryCheckData,
            index: number,
            column: CColumn<Device.HistoryCheckData>
          ) => {
            switch (column.dataIndex) {
              case 'checkdataList':
                return (
                  <div class="truncate">
                    {record.checkdataList.map((checkdata, idx) => {
                      return (
                        <span
                          class={[
                            'mx-1 inline-block border-warnning pr-2',
                            idx === record.checkdataList.length - 1
                              ? ''
                              : 'border-r',
                          ]}
                        >{`${checkdata.checkDataName || ''}: ${
                          checkdata.checkDataValue
                        }`}</span>
                      )
                    })}
                  </div>
                )
              default:
                return <div class="truncate">{text}</div>
            }
          },
        }}
      </CoustomTable>
    )
  },
})

const ExportCheckData = defineComponent({
  name: 'ExportCheckData',
  emits: ['finish'],
  setup(props, {emit}) {
    let downFileBtnLoading = ref(false)
    let {checkDevInfo} = toRefs(device_checkHistory_state)
    let {exportCheckData_source} = toRefs(device_checkHistory_state.modal)
    const handle_form_submit = async () => {
      downFileBtnLoading.value = true
      if (checkDevInfo.value && checkDevInfo.value?.devId) {
        let res = await exportCheckData({
          devId: checkDevInfo.value.devId,
          startTime: exportCheckData_source.value.startTime?.format(
            'YYYY-MM-DD 00:00:00'
          ),
          endTime: exportCheckData_source.value.endTime?.format(
            'YYYY-MM-DD 23:59:59'
          ),
        }).catch(err => {})
        if (res) {
          downFile(res.data, checkDevInfo.value.devName)
        }
      }
      downFileBtnLoading.value = false

      emit('finish', 'notRefresh')
    }
    return () => (
      <CoustomForm
        model={exportCheckData_source.value}
        loading={downFileBtnLoading.value}
        onFormSubmit={handle_form_submit}
        labelCol={{span: 4}}
        wrapperCol={{span: 20}}
        footerClass="text-right"
        submitBtnName="导出"
      >
        <a-form-item label="开始日期" name="startTime" class="mx-2 my-4">
          <a-date-picker
            class="w-full"
            v-model={[exportCheckData_source.value.startTime, 'value']}
            disabledDate={(current: Dayjs) => {
              return (
                current &&
                exportCheckData_source.value.endTime &&
                current > exportCheckData_source.value.endTime?.endOf('day')
              )
            }}
          />
        </a-form-item>
        <a-form-item label="结束日期" name="endTime" class="mx-2 my-4">
          <a-date-picker
            class="w-full"
            v-model={[exportCheckData_source.value.endTime, 'value']}
            disabledDate={(current: Dayjs) => {
              return (
                current &&
                exportCheckData_source.value.startTime &&
                current <=
                  exportCheckData_source.value.startTime
                    ?.endOf('day')
                    .subtract(1, 'day')
              )
            }}
          />
        </a-form-item>
      </CoustomForm>
    )
  },
})

/**设备列表 弹窗 */
export const CheckHistoryModel = defineComponent({
  setup(props, {emit}) {
    let {visible, type, title} = toRefs(device_checkHistory_state.modal)
    const handle_form_finish = (modelType?: 'notRefresh' | null) => {
      console.log(modelType)

      visible.value = false
      type.value = null
      switch (modelType) {
        case 'notRefresh':
          break
        default:
          // getTableDatas()
          break
      }
    }
    return () => {
      let dynamicCom = <div></div>
      switch (type.value) {
        case 'exportCheckData':
          dynamicCom = (
            <ExportCheckData
              onFinish={modelType => handle_form_finish(modelType)}
            ></ExportCheckData>
          )
          break
      }
      return (
        <a-modal
          visible={visible.value}
          title={title.value}
          footer={null}
          onCancel={() => {
            handle_form_finish()
          }}
        >
          {dynamicCom}
        </a-modal>
      )
    }
  },
})
